from solvers.solverbase import SolverBase
from solvers.analytical.analyticalbase import AnalyticalBase
from dolfin import *

class RungeKutta2(SolverBase,AnalyticalBase):
    'Second order explicit Runge-Kutta method.'
    def __init__(self,p=1):
        SolverBase.__init__(self,p)
        AnalyticalBase.__init__(self)

    def solve(self,problem):
        mesh = problem.domain

        p = self.p
        V = FunctionSpace(mesh,'CG',p)
        VV = VectorFunctionSpace(mesh,'CG',p)

        phi_ = interpolate(problem.phi_,V)
        phi1 = Function(V)                # this will be the solution of first system
        phi = TrialFunction(V)            # this turned into Function(V) will be solution of first and then second
        varphi = TestFunction(V)

        t = problem.t           
        dt = Constant(SolverBase._get_time_step(self,problem,VV,t))
        T = problem.T

        v = SolverBase._get_velocity(self,problem,VV,t)

        (ib,ib_value,bParts) = problem.get_inflowBCS()
        a = phi*varphi*dx
        if problem.weakBC:
            l1 = phi_*varphi*dx + dt*(inner(nabla_grad(varphi),v*phi_)*dx + nabla_div(v)*phi_*varphi*dx) # form for 1st 
            l = phi_*varphi*dx + 0.5*dt*(inner(nabla_grad(varphi),v*phi_)*dx + nabla_div(v)*phi_*varphi*dx)\
                               + 0.5*dt*(inner(nabla_grad(varphi),v*phi1)*dx + nabla_div(v)*phi1*varphi*dx) # form for 2nd
        else:
            n = FacetNormal(mesh)
            l1 = phi_*varphi*dx - dt*(phi_*varphi*inner(v,n)*ds(0) - inner(nabla_grad(varphi),v*phi_)*dx - nabla_div(v)*phi_*varphi*dx) # form for 1st 
            l = phi_*varphi*dx - 0.5*dt*(phi_*varphi*inner(v,n)*ds(0) - inner(nabla_grad(varphi),v*phi_)*dx - nabla_div(v)*phi_*varphi*dx)\
                               - 0.5*dt*(phi1*varphi*inner(v,n)*ds(0) - inner(nabla_grad(varphi),v*phi1)*dx - nabla_div(v)*phi1*varphi*dx) # form for 2nd

        self.update(problem,phi_,t,float(dt),0)  # store the solution at time 0
       
        A = assemble(a)
        phi = Function(V)
   
        t = float(dt)
        count = 1
        
        while t <= T:
            ibc = DirichletBC(V,ib_value(t),ib)
            L1 = assemble(l1,exterior_facet_domains=bParts) 
            ibc.apply(A,L1)
            solve(A,phi.vector(),L1)  #solve first system and assign the solution to phi1
            phi1.assign(phi)

            L = assemble(l,exterior_facet_domains=bParts)
            ibc.apply(A,L)            
            solve(A,phi.vector(),L)   #solve second system and assign the solution to phi_
            phi_.assign(phi)

            self.update(problem,phi_,t,float(dt),count)

            t += float(dt)
            count += 1

        problem.save_data(self.saveDir,str(self.CFL))

